package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.mapper.IncidentMapper;
import com.neudu.yiyang.mapper.CustomerMapper;
import com.neudu.yiyang.pojo.Incident;
import com.neudu.yiyang.pojo.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class IncidentController {

    @Autowired
    private IncidentMapper incidentMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private JSONReturn jsonReturn;

    @GetMapping("/list")
    public String getCustomerList() {
        try {
            LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Customer::getIsDeleted, 0); // 只查询未删除的客户
            queryWrapper.orderByAsc(Customer::getId); // 按ID排序

            List<Customer> customerList = customerMapper.selectList(queryWrapper);
            System.out.println("Customer List: " + customerList); // 打印客户列表
            return jsonReturn.returnSuccess(customerList);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取客户列表失败: " + e.getMessage());
        }
    }
    // 查询所有事件（带分页和条件查询）
    @PostMapping("/get_all_incidents")
    public String getAllIncidents(@RequestBody Map<String, Object> params) {
        try {
            int pageNum = params.get("pageNum") == null ? 1 : (int) params.get("pageNum");
            int pageSize = params.get("pageSize") == null ? 10 : (int) params.get("pageSize");
            String customerName = (String) params.get("customerName");

            PageHelper.startPage(pageNum, pageSize);

            LambdaQueryWrapper<Incident> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Incident::getIsDeleted, 0); // 只查询未删除的记录

            List<Incident> list = incidentMapper.selectList(queryWrapper);

            // 关联查询客户信息并过滤
            list = list.stream().filter(incident -> {
                if (incident.getCustomerId() != null) {
                    Customer customer = customerMapper.selectById(incident.getCustomerId());
                    incident.setCustomerName(customer.getCustomerName());
                    incident.setFamilyMember(customer.getFamilyMember());
                    incident.setContectTel(customer.getContactTel());
                    incident.setCustomerSex(customer.getCustomerSex()); // 添加设置客户性别
                    // 如果传入了customerName，则进行过滤
                    return customerName == null ||
                            customer.getCustomerName().contains(customerName);
                }
                return customerName == null; // 如果没有客户信息，且传入了customerName则过滤掉
            }).collect(Collectors.toList());

            PageInfo<Incident> pageInfo = new PageInfo<>(list);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("list", pageInfo.getList());
            result.put("total", pageInfo.getTotal());

            return jsonReturn.returnSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("查询失败: " + e.getMessage());
        }
    }

    // 新增一条事件记录
    @PostMapping("/add_incident")
    public String addIncident(@RequestBody Incident incident) {
        try {
            // 设置默认值
            if (incident.getIsDeleted() == null) {
                incident.setIsDeleted(0); // 默认未删除
            }
            if (incident.getIncidentTime() == null) {
                incident.setIncidentTime(new Date()); // 默认当前时间
            }
            if (incident.getIsNotified() == null) {
                incident.setIsNotified(0); // 默认未通知
            }

            int result = incidentMapper.insert(incident);
            return result > 0 ? jsonReturn.returnSuccess("添加成功") : jsonReturn.returnError("添加失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("添加失败: " + e.getMessage());
        }
    }

    // 修改一条事件记录
    @PutMapping("/modify_incident")
    public String modifyIncident(@RequestBody Incident incident) {
        try {
            if (incident.getId() == null) {
                return jsonReturn.returnError("ID不能为空");
            }

            int result = incidentMapper.updateById(incident);
            return result > 0 ? jsonReturn.returnSuccess() : jsonReturn.returnError("更新失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("更新失败: " + e.getMessage());
        }
    }

    // 删除一条事件记录（逻辑删除）
    @DeleteMapping("/remove_incident")
    public String removeIncident(@RequestParam("id") Integer id) {
        try {
            if (id == null) {
                return jsonReturn.returnError("ID不能为空");
            }

            Incident incident = new Incident();
            incident.setId(id);
            incident.setIsDeleted(1); // 设置为已删除

            int result = incidentMapper.updateById(incident);
            return result > 0 ? jsonReturn.returnSuccess() : jsonReturn.returnError("删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("删除失败: " + e.getMessage());
        }
    }

    // 通知家属
    @PostMapping("/notify_family")
    public String notifyFamily(@RequestBody Incident incident) {
        try {
            if (incident.getId() == null) {
                return jsonReturn.returnError("ID不能为空");
            }

            Incident existingIncident = incidentMapper.selectById(incident.getId());
            if (existingIncident == null) {
                return jsonReturn.returnError("事件记录不存在");
            }

            existingIncident.setIsNotified(1); // 标记为已通知
            existingIncident.setNotifier(incident.getNotifier());
            existingIncident.setNotificationTime(incident.getNotificationTime());

            int result = incidentMapper.updateById(existingIncident);
            return result > 0 ? jsonReturn.returnSuccess("通知成功") : jsonReturn.returnError("通知失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("通知失败: " + e.getMessage());
        }
    }
}